package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;


    /**
    *
    *新增
    * */
    @PostMapping
    public R save(@RequestBody Category category){
        boolean save = categoryService.save(category);
        if (save) {
            return R.success("新增分类添加成功");
        } else {
            return R.error("添加分类失败");
        }
    }

    /**
    * 分页查询
    * */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize){
        //分页构造器
        Page<Category> pageInfo = new Page<>(page,pageSize);
        //条件构造器
        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper<>();
        //根据订单排
        qw.orderByAsc(Category::getSort);
        //分页查询
        categoryService.page(pageInfo,qw);
        return R.success(pageInfo);
    }

    /**
    *
    * 删除分类,根据id删除
    * */
    @DeleteMapping
    public R<String> delete(Long id){
        categoryService.remove(id);
        return R.success("删除成功");
       /* boolean remove = categoryService.removeById(id);
        if(remove){
            return R.success("删除成功");
        }else {
            return R.error("删除失败");
        }*/

    }

    /**
    * 回显,根据id修改数据
    * */
    @GetMapping("/{id}")
    public R<Category> getById(@PathVariable Long id){
        Category category = categoryService.getById(id);
        if (category != null){
            return R.success(category);
        }else{
            return R.error("没有该菜品分类");
        }

    }

    /**
    *修改菜品分类
    * */
    @PutMapping
    public R<String> update(@RequestBody Category category){
        boolean update = categoryService.updateById(category);
        if (update){
            return R.success("修改成功");
        }else{
            return R.error("修改失败");
        }

    }

    /**
    * 根据条件查询分类数据
    * */
    @GetMapping("/list")
    public R list(Category category,Integer type){
        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper<>();
        qw.eq(category.getType() !=null,Category::getType,type);
        //根据订单和修改时间排序
        qw.orderByAsc(Category::getSort);
        qw.orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryService.list(qw);

        return R.success(list);
    }
}
